package IO;

import java.io.*;
import java.util.Scanner;

public class Demo13 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入");
        String path = scanner.next();
        System.out.println("请输入要查询的词：");
        String searchWord = scanner.next();

        File rootFile = new File(path);
        if (!rootFile.isDirectory()){
            System.out.println("当前输入路径非法！");
            return;
        }

        search(rootFile,searchWord);
    }

    private static void search(File rootFile, String searchWord) {
        File[] files = rootFile.listFiles();
        if (files == null){
//            空目录，递归结束条件
            return;
        }

        for (File f:files) {
            if (f.isFile()){
//                读取文件内容并搜索
                matchWord(f,searchWord);
            } else if (f.isDirectory()) {
//                递归的搜索子目录
                search(f,searchWord);
            }
        }
    }

    private static void matchWord(File f, String searchWord) {
        try (Reader reader = new FileReader(f)){
//            把读到的结果，最终构造到一个StringBuilder里
            StringBuilder stringBuilder = new StringBuilder();
            while(true){
                int c = reader.read();
                if (c == -1){
                    break;
                }
                stringBuilder.append((char) c);
            }
//            循环结束
            if (stringBuilder.indexOf(searchWord) >= 0){
//                找到了
                System.out.println("找到了匹配结果：" + f.getAbsolutePath());
            }
        }  catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
